<?php

namespace App\Console\Commands;

use App\Models\CheckOrder;
use App\Models\FlowChannel;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class MatchCheckOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check_order:match';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '匹配检测订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $redis = Redis::connection();

        //解绑所有检测订单并且清除redis数据，重新分配检测订单
        CheckOrder::query()->get()->each(function ($check_order) use ($redis) {
            if ($check_order->flow_channel_id != null) {
                $redis->del('check_order_' . $check_order->flowChannel->param);
                $check_order->flow_channel_id = null;
                $check_order->save();
            }
        });


        \App\Models\FlowChannelStat::query()->whereHas('flowChannel', function ($flowChannel) {
            //取没有检测订单的流量渠道
            return $flowChannel->whereDoesntHave('checkOrder');//取没有检测订单的流量渠道
        })->whereDate('date', Carbon::now()->toDateString())->groupBy('flow_channel_id')
            ->selectRaw('sum(pv) as total_pv,flow_channel_id')
            ->orderByDesc('total_pv')
            ->get()->each(function ($flow_channel) use ($redis) {
                //当前流量渠道没有检测订单，取出可用检测订单，绑定流量渠道
                $check_order = CheckOrder::query()->whereNull('flow_channel_id')->first();
                if (!is_null($check_order)) {
                    $check_order->flow_channel_id = $flow_channel->flow_channel_id;
                    $check_order->save();
                    //写入Redis

                    $html = file_get_contents($check_order->url);

                    preg_match("/property=\"og:url\" content=\"(\S+)\#/", $html, $arr);

                    $url = str_replace('amp;', '', $arr[1]);
                    $redis->hmset('check_order_' . $flow_channel->flowChannel->param, [
                        'url' => $url,
                        'check_order_id' => $check_order->id,
                        'flow_channel_id' => $flow_channel->flow_channel_id
                    ]);
                }
            });


    }
}
